from flask import Flask, request, jsonify
import pymysql

app = Flask(__name__)

# 数据库连接函数
def connect_db():
    return pymysql.connect(
        host="192.168.126.179",
        user="root",
        password="123456",
        port=3306,
        db="product_db",
        charset="utf8mb4"
    )

# 添加商品
@app.route('/add_product', methods=['POST'])
def add_product():
    data = request.json
    pro_name = data.get('pro_name')
    pro_price = data.get('pro_price')
    pro_stock = data.get('pro_stock')

    conn = connect_db()
    cursor = conn.cursor()

    try:
        sql = "INSERT INTO product (pro_name, pro_price, pro_stock) VALUES (%s, %s, %s)"
        cursor.execute(sql, (pro_name, pro_price, pro_stock))
        conn.commit()
        return jsonify({"status": "success", "message": "商品添加成功"})
    except pymysql.err.IntegrityError:
        conn.rollback()
        return jsonify({"status": "error", "message": "商品已存在，无法重复添加"}), 400
    except Exception as e:
        conn.rollback()
        return jsonify({"status": "error", "message": str(e)}), 500
    finally:
        cursor.close()
        conn.close()

# 查看商品
@app.route('/view_product/<string:pro_name>', methods=['GET'])
def view_product(pro_name):
    conn = connect_db()
    cursor = conn.cursor()

    sql = "SELECT pro_price, pro_stock FROM product WHERE pro_name = %s"
    cursor.execute(sql, (pro_name,))
    result = cursor.fetchone()

    if result:
        pro_price, pro_stock = result
        return jsonify({
            "status": "success",
            "data": {
                "pro_name": pro_name,
                "pro_price": pro_price,
                "pro_stock": pro_stock
            }
        })
    else:
        return jsonify({"status": "error", "message": "商品不存在！"}), 404

# 删除商品
@app.route('/delete_product/<string:pro_name>', methods=['DELETE'])
def delete_product(pro_name):
    conn = connect_db()
    cursor = conn.cursor()

    sql = "DELETE FROM product WHERE pro_name = %s"
    cursor.execute(sql, (pro_name,))

    if cursor.rowcount > 0:
        conn.commit()
        return jsonify({"status": "success", "message": f"商品 {pro_name} 已被删除！"})
    else:
        conn.rollback()
        return jsonify({"status": "error", "message": "商品不存在！"}), 404

# 修改商品
@app.route('/modify_product/<string:pro_name>', methods=['PUT'])
def modify_product(pro_name):
    data = request.json
    pro_price = data.get('pro_price')
    pro_stock = data.get('pro_stock')

    conn = connect_db()
    cursor = conn.cursor()

    sql = "UPDATE product SET pro_price = %s, pro_stock = %s WHERE pro_name = %s"
    cursor.execute(sql, (pro_price, pro_stock, pro_name))

    if cursor.rowcount > 0:
        conn.commit()
        return jsonify({"status": "success", "message": f"商品 {pro_name} 的信息已更新！"})
    else:
        conn.rollback()
        return jsonify({"status": "error", "message": "商品不存在！"}), 404

# 启动 Flask 应用
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)